#pragma once 

#include <iostream>
#include <queue>
#include <string>

#include "Tool.hpp"

#define CAPACITY 1024
using namespace std;


class MsgPool 
{
    public:
        MsgPool(size_t capacity = CAPACITY)
        {
            capacity_ = capacity;
            pthread_mutex_init(&mutex_lock_,NULL);
            pthread_cond_init(&con_lock_,NULL);
            pthread_cond_init(&pro_lock_,NULL);
        }
        ~MsgPool()
        {
            pthread_cond_destroy(&con_lock_);
            pthread_cond_destroy(&pro_lock_);
            pthread_mutex_destroy(&mutex_lock_);
        }
        //把信息传到消息池
        int RecvMsgToPool(string& msg)
        {
            pthread_mutex_lock(&mutex_lock_);
            while(que_msg_.size() >= capacity_)
            {
                pthread_cond_wait(&pro_lock_,&mutex_lock_);
            }
            que_msg_.push(msg);
            pthread_mutex_unlock(&mutex_lock_);
            pthread_cond_signal(&con_lock_);
            return 0;
        }
        //从消息池发送给在线的客户端
        int SendMsgToClient(string* msg)
        {
            pthread_mutex_lock(&mutex_lock_);
            while(que_msg_.empty()) 
            {
                pthread_cond_wait(&con_lock_,&mutex_lock_);
            }
            *msg = que_msg_.front();
            que_msg_.pop();
            pthread_mutex_unlock(&mutex_lock_);
            pthread_cond_signal(&pro_lock_);
            return 0;
        }
    private:
        //保存消息的容器
        queue<string> que_msg_;
        //容器的容量
        size_t  capacity_;
        //互斥锁和同步锁
        pthread_mutex_t mutex_lock_;
        pthread_cond_t con_lock_;
        pthread_cond_t pro_lock_;
};
